﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.ComponentModel;
using LinkShareWpf.Properties;
using System.IO;

namespace LinkShareWpf
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        string CoversPath = Settings.Default.CoversPath;

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            string _theme =Settings.Default.Theme;
            Uri langDictUri = new Uri("ResourceDictionaries/" + _theme, UriKind.Relative);
            ResourceDictionary langDict = Application.LoadComponent(langDictUri) as ResourceDictionary;
            Application.Current.Resources.MergedDictionaries.Clear();
            Application.Current.Resources.MergedDictionaries.Add(langDict);

            string IPserver = null;
            foreach (System.Net.IPAddress IP in System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName()))
                if (IP.ToString().Split('.')[0] == "151" || IP.ToString().Split('.')[0] == "172")
                {
                    IPserver = IP.ToString();
                    break;
                }
           // IPserver = "192.168.1.3";
            Settings.Default.UriServer = new UriBuilder(Uri.UriSchemeHttp, IPserver, Settings.Default.PortNumber, "LinkShareWpf").Uri;
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            try
            {
                String photolocation = CoversPath + @"\Temp";
                Uri uriPath = new Uri(photolocation);
                string[] files = Directory.GetFiles(uriPath.LocalPath);
                foreach (string file in files)
                    File.Delete(file);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                MessageBox.Show(ex.Message);
            }
            if (!CoversPath.Equals(Settings.Default.NewCoversPath))
            {
                try
                {
                    foreach (var file in Directory.GetFiles(CoversPath))
                        File.Move(file, Settings.Default.NewCoversPath + "\\" + Path.GetFileName(file));
                    Directory.CreateDirectory(Settings.Default.NewCoversPath + "\\Temp");
                    Directory.Delete(CoversPath + "\\Temp");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    MessageBox.Show(ex.Message);
                }
                Settings.Default.CoversPath = Settings.Default.NewCoversPath;
                Settings.Default.Save();
            }

        }

    }

}
